/**
 * 智慧小区管理系统 - 区域管理API接口
 * @author Wu.Liang
 * @date 2024-12-21
 * @updated 2024-12-21 - 完善区域管理API接口，遵循Controller命名规范
 */
import api from './request'
import type { ApiResponse } from './request'

// 区域数据类型定义
export interface RegionData {
  id: number
  regionName: string
  regionCode: string
  regionType: number
  parentId: number
  regionLevel: number
  sortOrder: number
  status: number
  createTime: string
  updateTime: string
  children?: RegionData[]
  // 区域树统计字段
  communityCount?: number
  buildingCount?: number
  householdCount?: number
  residentCount?: number
  occupancyRate?: number
  hasChildren?: boolean
  isLeaf?: boolean
  isRoot?: boolean
}

export interface CreateRegionDTO {
  regionName: string
  regionCode: string
  regionType: number
  parentId: number
  regionLevel: number
  sortOrder: number
  status: number
}

export interface UpdateRegionDTO {
  regionName?: string
  regionCode?: string
  regionType?: number
  parentId?: number
  regionLevel?: number
  sortOrder?: number
  status?: number
}

export interface RegionQueryDTO {
  regionName?: string
  regionCode?: string
  regionType?: number
  parentId?: number
  status?: number
  pageNum?: number
  pageSize?: number
  // 兼容性参数，支持current和size
  current?: number
  size?: number
}

// 分页响应类型
export interface PageResult<T> {
  records: T[]
  total: number
  size: number
  current: number
  pages: number
}

// 数据可视化相关类型定义
export interface PopulationStats {
  regionName: string
  regionCode: string
  population: number
  regionType: number
}

export interface CommunityDistribution {
  regionName: string
  communityCount: number
  percentage: number
}

export interface BuildingHouseholdTrend {
  date: string
  buildingCount: number
  householdCount: number
}

export interface AreaHeatmap {
  regionName: string
  regionCode: string
  area: number
  heatValue: number
  longitude: number
  latitude: number
}

export interface MapMarker {
  id: string
  name: string
  type: string
  longitude: number
  latitude: number
  iconUrl: string
  detail: unknown
}

export interface GeoSearchResult {
  address: string
  longitude: number
  latitude: number
  regionInfo: string
  communityInfo: string
}

export interface RegionBoundary {
  regionId: number
  regionName: string
  coordinates: Array<{
    longitude: number
    latitude: number
  }>
  style: {
    strokeColor: string
    strokeWeight: number
    fillColor: string
    fillOpacity: number
  }
}

// 区域API接口
export const regionApi = {
  /**
   * 获取区域树形结构（按需加载）
   * @author Wu.Liang
   */
  getRegionTree: (parentId?: number) => 
    api.get<ApiResponse<RegionData[]>>('/api/region/tree', { params: { parentId } }),

  /**
   * 获取区域完整树形结构（递归查询所有子区域）
   * @author Wu.Liang
   */
  getCompleteRegionTree: (parentId?: number) => 
    api.get<ApiResponse<RegionData[]>>('/api/region/tree/complete', { params: { parentId } }),

  /**
   * 获取区域列表
   * @author Wu.Liang
   */
  getRegionList: (params: RegionQueryDTO) => 
    api.get<ApiResponse<RegionData[]>>('/api/region', { params }),

  /**
   * 获取区域分页列表
   * @author Wu.Liang
   */
  getRegionPage: (params: RegionQueryDTO) => 
    api.get<ApiResponse<PageResult<RegionData>>>('/api/region', { params }),

  /**
   * 获取区域详情
   * @author Wu.Liang
   */
  getRegionDetail: (id: number) => 
    api.get<ApiResponse<RegionData>>(`/api/region/${id}`),

  /**
   * 获取区域层级路径
   * @author Wu.Liang
   */
  getRegionPath: (regionId: number) => 
    api.get<ApiResponse<RegionData[]>>(`/api/region/${regionId}/path`),

  /**
   * 获取子区域列表
   * @author Wu.Liang
   */
  getChildRegions: (regionId: number) => 
    api.get<ApiResponse<RegionData[]>>(`/api/region/${regionId}/children`),

  /**
   * 根据区域类型获取区域列表
   * @author Wu.Liang
   */
  getRegionsByType: (regionType: number) => 
    api.get<ApiResponse<RegionData[]>>(`/api/region/type/${regionType}`),

  /**
   * 根据区域编码获取区域
   * @author Wu.Liang
   */
  getRegionByCode: (regionCode: string) => 
    api.get<ApiResponse<RegionData>>(`/api/region/code/${regionCode}`),

  /**
   * 创建区域
   * @author Wu.Liang
   */
  createRegion: (data: CreateRegionDTO) => 
    api.post<ApiResponse<void>>('/api/region', data),

  /**
   * 更新区域
   * @author Wu.Liang
   */
  updateRegion: (id: number, data: UpdateRegionDTO) => 
    api.put<ApiResponse<void>>(`/api/region/${id}`, data),

  /**
   * 删除区域
   * @author Wu.Liang
   */
  deleteRegion: (id: number) => 
    api.delete<ApiResponse<void>>(`/api/region/${id}`),

  /**
   * 获取区域统计信息
   * @author Wu.Liang
   */
  getRegionStatistics: (params?: any) => 
    api.get<ApiResponse<any>>('/api/region/statistics', { params }),

  // ==================== 数据可视化接口 ====================

  /**
   * 获取区域人口统计（柱状图）
   * @author Wu.Liang
   */
  getPopulationStats: (params?: any) => 
    api.get<ApiResponse<PopulationStats[]>>('/api/region/visualization/population', { params }),

  /**
   * 获取小区分布统计（饼图）
   * @author Wu.Liang
   */
  getCommunityDistribution: (params?: any) => 
    api.get<ApiResponse<CommunityDistribution[]>>('/api/region/visualization/community-distribution', { params }),

  /**
   * 获取楼栋房户趋势统计（折线图）
   * @author Wu.Liang
   */
  getBuildingHouseholdTrend: (params?: any) => 
    api.get<ApiResponse<BuildingHouseholdTrend[]>>('/api/region/visualization/building-household-trend', { params }),

  /**
   * 获取区域面积热力图数据
   * @author Wu.Liang
   */
  getAreaHeatmap: (params?: any) => 
    api.get<ApiResponse<AreaHeatmap[]>>('/api/region/visualization/area-heatmap', { params }),

  /**
   * 获取地图标记数据
   * @author Wu.Liang
   */
  getMapMarkers: (type?: string, parentId?: number) => 
    api.get<ApiResponse<MapMarker[]>>('/api/region/visualization/map-markers', { params: { type, parentId } }),

  /**
   * 地理信息查询
   * @author Wu.Liang
   */
  geoSearch: (address?: string, longitude?: number, latitude?: number) => 
    api.get<ApiResponse<GeoSearchResult>>('/api/region/visualization/geo-search', { 
      params: { address, longitude, latitude } 
    }),

  /**
   * 获取区域边界数据
   * @author Wu.Liang
   */
  getRegionBoundary: (regionId: number) => 
    api.get<ApiResponse<RegionBoundary>>(`/api/region/visualization/region-boundary/${regionId}`)
}

// 数据权限管理API - 新增数据权限控制接口
export const dataScopeApi = {
  // 获取当前用户数据权限信息
  getDataScopeInfo: () => {
    return api.get<{
      code: number
      data: {
        userId: number
        isSuperAdmin: boolean
        isPropertyCompanyUser: boolean
        isOwnerUser: boolean
        communityIds: number[]
        propertyCompanyIds: number[]
        restrictions: string
        isSuperAdmin: boolean
        scopeDescription: string
      }
    }>('/api/region/data-scope/current-user')
  },

  // 检查用户是否有指定小区权限
  checkCommunityPermission: (communityId: number) => {
    return api.get<{
      code: number
      data: { hasPermission: boolean }
    }>(`/api/region/data-scope/community/${communityId}/check`)
  },

  // 批量检查用户小区权限
  batchCheckCommunityPermissions: (communityIds: number[]) => {
    return api.post<{
      code: number
      data: { authorizedCommunityIds: number[] }
    }>('/api/region/data-scope/community/batch-check', {
      communityIds
    })
  },

  // 获取用户可访问的小区列表
  getUserCommunities: () => {
    return api.get<{
      code: number
      data: number[]
    }>('/api/region/data-scope/user-communities')
  },

  // 刷新用户权限缓存
  refreshUserPermissionCache: () => {
    return api.post<{
      code: number
      data: { success: boolean }
    }>('/api/region/data-scope/refresh-cache')
  },

  // 清除用户权限缓存
  clearUserPermissionCache: (userId?: number) => {
    return api.delete<{
      code: number
      data: { success: boolean }
    }>('/api/region/data-scope/clear-cache', {
      params: { userId }
    })
  }
} 